﻿using Essensoft.Paylinks.WeChatPay.Client;
using Essensoft.Paylinks.WeChatPay.Payments.Domain;
using Essensoft.Paylinks.WeChatPay.Payments.Model;
using Essensoft.Paylinks.WeChatPay.Payments.Request;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Pay.Core.WechatPayCore
{
    /// <summary>
    /// JSAPI支付
    /// </summary>
    /// <param name="client"></param>
    /// <param name="options"></param>
    public class JSAPIPay(IWeChatPayClient client, WeChatPayClientOptions options)
    {
        public async Task<string> PayAsync(WeChatPayTransactionsJsapiBodyModel model)
        {
            model = new WeChatPayTransactionsJsapiBodyModel
            {
                AppId = options.AppId,
                MchId = options.MchId,
                Description = "JSAPI下单测试",
                OutTradeNo = DateTimeOffset.Now.ToString("yyyyMMddHHmmssfff"),
                NotifyUrl = "https://www.domain.com/WeChatPay/Payments/Notify/TransactionSuccess",
                Amount = new CommReqAmountInfo { Total = 1 },
                Payer = new JsapiReqPayerInfo { OpenId = string.Empty }
            };
            var request = new WeChatPayTransactionsJsapiRequest();
            request.SetBodyModel(model);
            var response = await client.ExecuteAsync(request, options);
            if (response.IsSuccessful)
            {
                var sdkRequest = new WeChatPayJsapiTransferPaymentRequest { AppId = model.AppId, Package = "prepay_id=" + response.PrepayId };
                var sdkResponse = await client.SdkExecuteAsync(sdkRequest, options);
                return JsonSerializer.Serialize(sdkResponse);
            }
            return response.Body;
        }
    }
}
